<?php
include_once dirname(__FILE__) . '/vendor/autoload.php';
include_once dirname(__FILE__) . '/Pcache.php';

Class Functions
{
	/**
	 * 用户ID
	 */
	const USER_KEY = "RSA:USER:KEY";
	/**
	 * 自增key
	 */
	const ID_INCR = "RSA:ID:INCR";
	/**
	 *用户详情
	 */
	const USER_DEATIL = "RSA:USER:DETAIL:%d";
	/**
	 * 系统
	 */
	const SERVER_DEATIL = "RSA:SERVER:DETAIL:%d";
	/**
	 * 加密方式
	 */
	const DIGEST_ALG = "sha512";
	/**
	 * 字符长度
	 */
	const PRIVATE_KEY_BITS = 4096; //字节数    512 1024  2048   4096 等
	/**
	 * 秘钥类型
	 */
	const PRIVATE_KEY_TYPE = OPENSSL_KEYTYPE_RSA;//加密类型

//	const OPENSSL_CONF = "D://phpstudy_pro//Extensions//php\php7.0.9nts//extras//ssl//openssl.cnf";
	const OPENSSL_CONF = "c://usr//local//ssl//openssl.cnf";

	/**
	 * 字段
	 * @var array
	 */
	public static $field = [
		"NAME",
		"KEY",
		"SCRIPT",
		"PRIVATEKEY",
		"PUBLICKEY",
		"CREATEAT"
	];

	/**
	 *******************************************************
	 * Name: getUser
	 * User: gong.chixin
	 * Date: 2019/12/24 11:39
	 *******************************************************
	 */
	public static function getUser()
	{
		$predis     = Pcache::create();
		$userIDList = $predis->SMEMBERS(self::USER_KEY);
		$userList   = array();
		foreach ($userIDList as $index => $id) {
			$key      = sprintf(self::USER_DEATIL, $id);
			$userName = $predis->hget($key, 'NAME');
			array_push($userList, [
									'id'       => $id,
									'userName' => $userName,
								]
			);
		}
		return !empty($userList) ? $userList : [];
	}

	//************************************处理密文************************************************

	/**
	 * 制作秘钥
	 * @param array $field
	 */
	public static function makePrivateKey($userScript = "")
	{
		$private_key = "";
		$publicKey   = "";
		$config      = array(
			'config'           => self::OPENSSL_CONF,
			"digest_alg"       => self::DIGEST_ALG,
			"private_key_bits" => self::PRIVATE_KEY_BITS,
			"private_key_type" => self::PRIVATE_KEY_TYPE,
		);
		$privateKey  = openssl_pkey_new($config);
		if (!$privateKey) {
			$str = "";
			while ($message = openssl_error_string()) {
				$str .= $message . "<br/>";
			}
			throw new Exception($str);
		}
		openssl_pkey_export($privateKey, $private_key, $userScript, $config);
		$publicKey = openssl_pkey_get_details($privateKey);

		return [$private_key, $publicKey];
	}



	/**
	 * 私钥加密
	 * @author maaibo
	 * @param 明文的加密内容
	 * @return 返回加密后内容
	 */
	public function PrivateEncrypt($data)
	{
		$crypto = '';
		foreach (str_split($data, 117) as $chunk) {
			openssl_private_encrypt($chunk, $encryptData, $this->pi_key);
			$crypto .= $encryptData;
		}
		$encrypted = $this->urlsafe_b64encode($crypto);//加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的
		return $encrypted;
	}

	/** 私钥加密的内容通过公钥可用解密出来
	 * @param $string
	 * @return mixed|string
	 */
	public function PublicDecrypt($encrypted)
	{
		// $encrypted = $this->urlsafe_b64decode($encrypted);
		$crypto = '';
		foreach (str_split($this->urlsafe_b64decode($encrypted), 128) as $chunk) {
			openssl_public_decrypt($chunk, $decryptData, $this->pu_key);
			$crypto .= $decryptData;
		}
		//openssl_public_decrypt($encrypted,$decrypted,$this->pu_key);//私钥加密的内容通过公钥可用解密出来
		return $crypto;
	}

	/** 公钥加密
	 * @param $string
	 * @return mixed|string
	 */
	public function PublicEncrypt($data)
	{
		$crypto = '';
		foreach (str_split($data, 117) as $chunk) {
			openssl_public_encrypt($chunk, $encryptData, $this->pu_key);
			$crypto .= $encryptData;
		}
		$encrypted = $this->urlsafe_b64encode($crypto);
		return $encrypted;
	}

	/** 私钥解密
	 * @param $string
	 * @return mixed|string
	 */
	public function PrivateDecrypt($encrypted)
	{
		$crypto = '';
		foreach (str_split($this->urlsafe_b64decode($encrypted), 128) as $chunk) {
			openssl_private_decrypt($chunk, $decryptData, $this->pi_key);
			$crypto .= $decryptData;
		}
		return $crypto;
	}
	//***********************************************************************************************


	/**
	 * @param array $field
	 */
	public static function view($view = '', array $params = [])
	{
		$view      = is_null($view) ? 'index' : $view;
		$file_path = dirname(__FILE__) . '/view/' . $view . '.php';
		if (!file_exists($file_path)) {
			throw new Exception($view . ":this View is not found!!!");
		}
		if ($params) {
			$params = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
			parse_str($params);
		}
		include_once($file_path);
	}

	/**
	 *******************************************************
	 * Name: errorMsg
	 * @param string $href
	 * @param string $msg
	 * @param int    $exp
	 * User: gong.chixin
	 * Date: 2019/12/24 13:33
	 *******************************************************
	 */
	public static function errorMsg($msg = "", $href = "", $exp = 2000)
	{
		$href = $href ? $href : $_SERVER['HTTP_REFERER'];
		$str  = <<<STR
<script type="text/javascript">
	document.write("<h1>{$msg}</h1>");
	setTimeout(function () {
		window.location.href="{$href}";
	},{$exp})
</script>
STR;
		echo $str;
		die;
	}
}